from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.conf import settings
from django.core.files.base import ContentFile
import requests
import json
import uuid
import logging
from datetime import datetime
from .models import MusicComposition, AudioSynthesis
from .baidu_auth import baidu_auth

logger = logging.getLogger(__name__)


def music_list(request):
    """AI音乐创作列表"""
    compositions = MusicComposition.objects.all().order_by('-created_at')
    return render(request, 'ai_music/music_list.html', {
        'compositions': compositions
    })


def create_music(request):
    """AI音乐创作表单"""
    if request.method == 'POST':
        title = request.POST.get('title')
        style = request.POST.get('style')
        description = request.POST.get('description')
        
        if title and style and description:
            if request.user.is_authenticated:
                user = request.user
            else:
                from django.contrib.auth.models import User
                user, created = User.objects.get_or_create(username='anonymous')
            
            MusicComposition.objects.create(
                user=user,
                title=title,
                style=style,
                description=description
            )
            messages.success(request, '音乐创作任务已创建！')
            return redirect('ai_music:music_list')
        else:
            messages.error(request, '请填写所有字段')
    
    return render(request, 'ai_music/create_music.html')


def audio_synthesis_list(request):
    """音频合成列表"""
    syntheses = AudioSynthesis.objects.all().order_by('-created_at')
    return render(request, 'ai_music/audio_synthesis_list.html', {
        'syntheses': syntheses
    })


def create_audio_synthesis(request):
    """创建音频合成任务"""
    if request.method == 'POST':
        text_content = request.POST.get('text_content')
        voice_type = request.POST.get('voice_type', '0')
        speed = int(request.POST.get('speed', 5))
        pitch = int(request.POST.get('pitch', 5))
        volume = int(request.POST.get('volume', 5))
        
        if text_content:
            if request.user.is_authenticated:
                user = request.user
            else:
                from django.contrib.auth.models import User
                user, created = User.objects.get_or_create(username='anonymous')
            
            AudioSynthesis.objects.create(
                user=user,
                text_content=text_content,
                voice_type=voice_type,
                speed=speed,
                pitch=pitch,
                volume=volume
            )
            messages.success(request, '音频合成任务已创建！')
            return redirect('ai_music:audio_synthesis_list')
        else:
            messages.error(request, '请输入要合成的文本内容')
    
    return render(request, 'ai_music/create_audio_synthesis.html')


@csrf_exempt
@require_http_methods(["POST"])
def audio_synthesize_api(request):
    """百度千帆音频合成API"""
    try:
        # 解析请求参数
        if request.content_type == 'application/json':
            data = json.loads(request.body)
        else:
            data = request.POST
        
        text_content = data.get('tex', '').strip()  # 百度API使用tex参数
        voice_type = data.get('per', '0')  # 发音人选择
        speed = int(data.get('spd', 5))  # 语速
        pitch = int(data.get('pit', 5))  # 音调
        volume = int(data.get('vol', 5))  # 音量
        audio_format = data.get('aue', 3)  # 音频格式，3为mp3
        
        if not text_content:
            return JsonResponse({
                'success': False,
                'error': '文本内容不能为空'
            }, status=400)
        
        if len(text_content) > 1024:
            return JsonResponse({
                'success': False,
                'error': '文本内容过长，最多1024个字符'
            }, status=400)
        
        # 获取访问令牌
        try:
            access_token = baidu_auth.get_access_token()
        except Exception as e:
            logger.error(f"获取百度Access Token失败: {str(e)}")
            return JsonResponse({
                'success': False,
                'error': f'获取访问令牌失败: {str(e)}'
            }, status=500)
        
        # 准备请求参数 - 使用GET请求方式
        tts_params = {
            'tex': text_content,
            'per': voice_type,
            'spd': speed,
            'pit': pitch,
            'vol': volume,
            'aue': audio_format,
            'cuid': str(uuid.uuid4()),  # 用户唯一标识
            'lan': 'zh',  # 语言设置为中文
            'ctp': 1,  # 客户端类型
            'tok': access_token  # 使用tok参数传递token
        }
        
        tts_url = settings.BAIDU_QIANFAN_CONFIG['TTS_URL']
        
        logger.info(f"开始调用百度音频合成API: {text_content[:50]}...")
        
        # 使用GET请求调用百度API
        response = requests.get(
            tts_url,
            params=tts_params,
            timeout=60
        )
        
        # 检查响应
        if response.status_code != 200:
            logger.error(f"百度API请求失败: HTTP {response.status_code}")
            return JsonResponse({
                'success': False,
                'error': f'API请求失败: HTTP {response.status_code}'
            }, status=500)
        
        # 检查响应内容类型
        content_type = response.headers.get('Content-Type', '')
        
        if 'audio' in content_type:
            # 成功返回音频数据
            audio_data = response.content
            
            # 保存到数据库
            if request.user.is_authenticated:
                user = request.user
            else:
                from django.contrib.auth.models import User
                user, created = User.objects.get_or_create(username='anonymous')
            
            # 创建文件名
            timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
            filename = f'tts_{timestamp}_{uuid.uuid4().hex[:8]}.mp3'
            
            # 保存文件
            synthesis = AudioSynthesis.objects.create(
                user=user,
                text_content=text_content,
                voice_type=voice_type,
                speed=speed,
                pitch=pitch,
                volume=volume,
                status='completed',
                file_size=len(audio_data)
            )
            
            synthesis.audio_file.save(
                filename,
                ContentFile(audio_data),
                save=True
            )
            
            logger.info(f"音频合成成功: {synthesis.id}, 文件大小: {len(audio_data)} bytes")
            
            return JsonResponse({
                'success': True,
                'message': '音频合成成功',
                'data': {
                    'synthesis_id': synthesis.id,
                    'audio_url': synthesis.audio_file.url,
                    'file_size': len(audio_data),
                    'text_preview': text_content[:50] + '...' if len(text_content) > 50 else text_content
                }
            })
        else:
            # 错误响应，解析错误信息
            logger.error(f"百度API响应内容类型: {content_type}")
            logger.error(f"百度API响应内容: {response.text[:500]}")
            
            try:
                error_data = response.json()
                error_msg = error_data.get('error_msg', '未知错误')
                error_code = error_data.get('error_code', 'unknown')
                logger.error(f"百度API返回错误: {error_code} - {error_msg}")
                
                return JsonResponse({
                    'success': False,
                    'error': f'百度API错误: {error_msg}',
                    'error_code': error_code,
                    'response_content': response.text[:200]
                }, status=400)
            except:
                logger.error(f"百度API返回非预期响应: {response.text[:200]}")
                return JsonResponse({
                    'success': False,
                    'error': 'API返回非预期响应',
                    'response_content': response.text[:200]
                }, status=500)
        
    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'error': '请求参数格式错误'
        }, status=400)
    except Exception as e:
        logger.error(f"音频合成处理异常: {str(e)}")
        return JsonResponse({
            'success': False,
            'error': f'处理失败: {str(e)}'
        }, status=500)


def audio_detail(request, synthesis_id):
    """音频合成详情"""
    synthesis = get_object_or_404(AudioSynthesis, id=synthesis_id)
    return render(request, 'ai_music/audio_detail.html', {
        'synthesis': synthesis
    })


def audio_proxy(request, synthesis_id):
    """音频文件代理服务"""
    try:
        synthesis = get_object_or_404(AudioSynthesis, id=synthesis_id)
        
        if synthesis.audio_file:
            # 读取音频文件
            with open(synthesis.audio_file.path, 'rb') as f:
                audio_data = f.read()
            
            # 返回音频响应
            response = HttpResponse(audio_data, content_type='audio/mpeg')
            response['Content-Disposition'] = f'inline; filename="{synthesis.audio_file.name}"'
            response['Content-Length'] = str(len(audio_data))
            return response
        else:
            return HttpResponse('音频文件不存在', status=404)
            
    except AudioSynthesis.DoesNotExist:
        return HttpResponse('音频记录不存在', status=404)
    except FileNotFoundError:
        return HttpResponse('音频文件不存在', status=404)
    except Exception as e:
        logger.error(f"音频代理服务错误: {str(e)}")
        return HttpResponse('服务器错误', status=500)
